package xiaopiya.robot.handler.translate;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

/**
 * Google翻译机
 * 
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class GoogleTranslater
{
	private final static Log LOG = LogFactory.getLog(GoogleTranslater.class);

	private XMPPConnection xmppConnection;

	private ChatManager chatmanager;

	private String username;

	private String password;

	public GoogleTranslater(String username, String password)
	{
		this.username = username;
		this.password = password;
	}

	public void start() throws XMPPException
	{
		if (LOG.isInfoEnabled())
		{
			LOG.info("Start Google Translator[username=" + this.username
					+ ",password=" + this.password + "]");
		}

		ConnectionConfiguration config = new ConnectionConfiguration(
				"talk.google.com", 5222, "gmail.com");
		config.setSASLAuthenticationEnabled(true);
		config.setReconnectionAllowed(true);
		xmppConnection = new XMPPConnection(config);

		connectAndLoginIfNeeded();

		if (LOG.isInfoEnabled())
		{
			LOG.info("Start Google Translator[username=" + this.username
					+ ",password=" + this.password + "] Success!");
		}

	}

	private void connectAndLoginIfNeeded() throws XMPPException
	{
		if (!this.xmppConnection.isConnected())
		{
			this.xmppConnection.connect();
			this.xmppConnection.login(this.username, this.password);

			this.chatmanager = this.xmppConnection.getChatManager();
		}
	}

	public String translate(String source) throws XMPPException
	{
		if (source == null)
		{
			return "";
		}
		Chat chat = null;

		final BlockingQueue<String> result = new ArrayBlockingQueue<String>(1);

		MessageListener messagListener = new MessageListener()
		{
			public void processMessage(Chat chat, Message message)
			{
				if (LOG.isInfoEnabled())
				{
					LOG.info("Received message: " + message.getBody());
				}
				result.add(message.getBody());
			}
		};

		connectAndLoginIfNeeded();

		source = source.trim();
		if (source.length() == 0)
		{
			return "";
		}
		int first = source.charAt(0);
		// 英文
		if ((first >= 'A' && first <= 'Z') || (first >= 'a' && first <= 'z'))
		{
			chat = chatmanager.createChat("en2zh@bot.talk.google.com",
					messagListener);

		} else
		{
			chat = chatmanager.createChat("zh2en@bot.talk.google.com",
					messagListener);
		}
		chat.sendMessage(source);
		try
		{
			return result.poll(2, TimeUnit.SECONDS);
		} catch (InterruptedException e)
		{
			LOG.error("error when get google result", e);
			return null;
		}
	}

	public void shutdown()
	{
		if (this.xmppConnection != null)
		{
			this.xmppConnection.disconnect();
		}
	}
}